package com.scy.edu.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author 司晨雨
 * @date 2020/8/22 22:53
 * @description
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() >= 4) {
            int bytes = in.readInt();
            byte[] data = new byte[bytes];
            in.readBytes(data);
            Object obj = serializer.deserialize(clazz, data);
            out.add(obj);
        }
    }


}
